package backend_package;

import java.util.Observable;
import java.util.Observer;
import database_package.SqliteDatabase;
import frontend_package.LoginPanel;
/**
 * The Login class that deals with LoginPanel and Database. 
 * It checks the Database if user is registered.
 * @author Kyler
 * @author Syrym
 * @version 12/12/2014
 * */
public class Login extends Observable implements Observer{

	/**
	 * @author Kyler
	 */
	public Login(){
		super();
	}
	/**
	 * 
	 * This method sends user information to this class's observers
	 * @author Syrym Satanov
	 * @date 12-2-14
	 * @param packet the packet that contains information about the user from DB
	 */
	private void checkUser(Packet packet){
		setChanged();
		notifyObservers(packet); //notifies DB 
	}
	
	/**
	 * 
	 * @author Syrym Satanov
	 * @author Kyler Nelson [minor]
	 * date 12-2-14
	 * 
	 * @param packet the packet that contains information about the user from DB
	 * checks whether the user is an analyst or admin and sends the appropriate messages
	 * to the panels that will open based on the information
	 */
	private void checkDBresult(Packet packet){
		boolean isUser = (boolean)packet.get(0);
		boolean isAdmin = (boolean)packet.get(1);

		if(isUser && !isAdmin){ //analyst
			setChanged();
			notifyObservers(new Packet("l_analystchosen_a")); //notify analyst
			setChanged();
			notifyObservers(new Packet("l_analystchosen_m")); //Notify MainFrame
		} else if(isUser && isAdmin){ //admin
			setChanged();
			notifyObservers(new Packet("ad_adminchosen_m")); //Notify MainFrame
		} else { // not registered
			setChanged();
			notifyObservers(new Packet("l_notuser"));//Notify LoginPanel
		}
	}
	@Override
	/**
	 * 
	 * @author Syrym Satanov
	 * 
	 * date 12-2-14
	 * 
	 * @param o the object that this class is observing
	 * @param args the packet that contains information about the user
	 */
	public void update(Observable o, Object arg) {
		Packet packet = (Packet)arg;
		if(o instanceof LoginPanel && packet.getTag().equals("lp_isvaliduser")){
			checkUser(packet);
		} else if(o instanceof SqliteDatabase && packet.getTag().equals("db_isvaliduser")){

			checkDBresult(packet);
		}
	}
}
